import 'package:built_collection/built_collection.dart';
import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/collection_list_item/collection_list_item.dart';
import 'package:mobile_app.core/core/domain/entities/premium_access_status.dart';
import 'package:mobile_app.home.collections/single_custom_collection_folder_page/domain/helpers/find_custom_collection_folder/helper.dart';
import 'package:mobile_app.home.core/core/domain/helpers/get_permitted_collection_list_item_ids/helper.dart';

part 'failures.dart';

part 'result.dart';

abstract class HandleCollectionCreationLearningContentOuterUpdate {
  Either<CollectionCreationLearningContentOuterUpdateHandlingFailure,
      CollectionCreationLearningContentOuterUpdateHandlingResult> call({
    required String collectionFolderId,
    required PremiumAccessStatus premiumAccessStatus,
    required BuiltList<CollectionListItem> collectionListItems,
  });
}

class HandleCollectionCreationLearningContentOuterUpdateImpl
    implements HandleCollectionCreationLearningContentOuterUpdate {
  const HandleCollectionCreationLearningContentOuterUpdateImpl({
    required FindCustomCollectionFolder findCustomCollectionFolder,
    required GetPermittedCollectionListItemIds getPermittedCollectionListItemIds,
  })  : _findCustomCollectionFolder = findCustomCollectionFolder,
        _getPermittedCollectionListItemIds = getPermittedCollectionListItemIds;

  final FindCustomCollectionFolder _findCustomCollectionFolder;
  final GetPermittedCollectionListItemIds _getPermittedCollectionListItemIds;

  @override
  Either<CollectionCreationLearningContentOuterUpdateHandlingFailure,
      CollectionCreationLearningContentOuterUpdateHandlingResult> call({
    required String collectionFolderId,
    required PremiumAccessStatus premiumAccessStatus,
    required BuiltList<CollectionListItem> collectionListItems,
  }) {
    final collectionFolder = _findCustomCollectionFolder(
      customCollectionFolderId: collectionFolderId,
      collectionListItems: collectionListItems,
    );

    if (collectionFolder == null) {
      const failure =
          NonexistentCollectionFolderCollectionCreationLearningContentOuterUpdateHandlingFailure();
      return left(failure);
    }

    final permittedCollectionListItemIds = _getPermittedCollectionListItemIds(
      collectionListItems: collectionListItems,
      premiumAccessStatus: premiumAccessStatus,
    );

    final result = CollectionCreationLearningContentOuterUpdateHandlingResult(
      collectionFolder: collectionFolder,
      permittedCollectionListItemIds: permittedCollectionListItemIds,
    );

    return right(result);
  }
}
